package com.hope.onlinestudy.fragment.web

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.view.View
import android.webkit.*
import com.hope.onlinestudy.R
import com.hope.onlinestudy.activity.start.StartActivity
import com.hope.onlinestudy.mvp.MVPBaseFragment
import com.hope.onlinestudy.utils.ApiUtils
import com.hope.onlinestudy.utils.Utils
import kotlinx.android.synthetic.main.view_webview.*
import org.jetbrains.anko.support.v4.toast

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
class WebFragment : MVPBaseFragment<WebContract.View, WebPresenter>(), DownloadListener,
    WebContract.View {
    private var urlPath: String? = ""
    private var home: Boolean? = false

    companion object {
        fun instance(urlPath: String, home: Boolean = false): WebFragment {
            val fragment = WebFragment()
            val bund = Bundle().apply {
                putString("url", urlPath)
                putBoolean("home", home)
            }
            fragment.arguments = bund
            return fragment
        }
    }

    override fun onDownloadStart(
        url: String?,
        userAgent: String?,
        contentDisposition: String?,
        mimetype: String?,
        contentLength: Long
    ) {
        Utils.logs("tag", "要下载的url$url")
        downloadByBrowser(url!!)
    }

    override fun initView(): Int {
        return R.layout.view_webview
    }

    private fun downloadByBrowser(url: String) {
        startActivity(
            Intent(Intent.ACTION_VIEW).addCategory(Intent.CATEGORY_APP_BROWSER)
                .setData(Uri.parse(url))
        )
    }

    @SuppressLint("NewApi", "SetJavaScriptEnabled", "AddJavascriptInterface")
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    override fun bindData() {
        val startActivity: StartActivity = activity as StartActivity

        urlPath =
            "${ApiUtils.configModel?.sys_base_url}${ApiUtils.configModel?.sys_h5_context}${arguments?.getString(
                "url"
            )}"
        home = arguments?.getBoolean("home", false)
        val token = "javascript:dispatchJwtToken('${ApiUtils.loginModel?.jwtToken}')"

        val webSettings = wvView.settings
        webSettings.javaScriptEnabled = true//允许使用js
        webSettings.cacheMode = WebSettings.LOAD_DEFAULT
        webSettings.allowUniversalAccessFromFileURLs = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.allowFileAccess = true
        //支持屏幕缩放
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        webSettings.displayZoomControls = true
        webSettings.domStorageEnabled = true
        wvView.addJavascriptInterface(this, "android")//添加js监听 这样html就能调用客户端
        wvView.setDownloadListener(this)

        wvView.webChromeClient = object : WebChromeClient() {
            private var mCustomView: View? = null
            private var mCustomViewCallback: CustomViewCallback? = null
            override fun onJsAlert(
                view: WebView,
                url: String,
                message: String,
                result: JsResult
            ): Boolean {
                AlertDialog.Builder(activity)
                    .setTitle("提示").setMessage(message).show()
                return super.onJsAlert(view, url, message, result)
            }

            override fun onShowFileChooser(
                webView: WebView?,
                filePathCallback: ValueCallback<Array<Uri>>?,
                fileChooserParams: FileChooserParams?
            ): Boolean {
                val i = Intent(Intent.ACTION_GET_CONTENT)
                i.addCategory(Intent.CATEGORY_OPENABLE)
                i.type = "text/*"
                startActivityForResult(
                    Intent.createChooser(
                        i,
                        "选择文件"
                    ), 1001
                )

                return true
            }

            @SuppressLint("SourceLockedOrientationActivity")
            override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
                if (mCustomView != null) {
                    callback?.onCustomViewHidden()
                    return
                }
                startActivity.hideNavgiationBar(true)
                mCustomView = view
                mFrameLayout.addView(mCustomView)
                mCustomViewCallback = callback
                wvView.visibility = View.GONE
                activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                super.onShowCustomView(view, callback)
            }

            @SuppressLint("SourceLockedOrientationActivity")
            override fun onHideCustomView() {
                wvView.visibility = View.VISIBLE
                if (mCustomView == null) {
                    return
                }
                startActivity.hideNavgiationBar(false)
                mCustomView?.visibility = View.GONE
                mFrameLayout.removeView(mCustomView)
                mCustomViewCallback?.onCustomViewHidden()
                mCustomView = null
                activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                super.onHideCustomView()
            }

        }
        wvView.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                wvView?.loadUrl(token)
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }
        }
        if (home!!)
            wvView.loadUrl(urlPath)

        Utils.logs("tag", "path  =$urlPath")
    }

    override fun lazyLoad() {
        if (null != wvView && !home!!) {
            wvView.loadUrl(urlPath)
        }
    }

    override fun onResume() {
        super.onResume()
        wvView.onResume()
    }

    override fun onPause() {
        super.onPause()
        wvView.onPause()
    }

    /**
     * JS调用android的方法
     * @param str
     * @return
     */
    @JavascriptInterface
    fun getClient(str: String) {
        Utils.logs("tag", "从js传过来的值 = $str")
        toast(str)
    }

    @JavascriptInterface //仍然必不可少
    fun goback() {
    }

    public override fun onDestroy() {
        super.onDestroy()
        if (null != wvView)
            wvView.destroy()
    }
}